/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.agenda;

import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.HasExecutionListeners;
import com.je.bpm.engine.Agenda;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntityManager;
import com.je.bpm.engine.impl.util.ProcessDefinitionUtil;
import com.je.bpm.core.model.process.Process;

/**
 * Abstract superclass for all operation interfaces (which are {@link Runnable} instances),
 * exposing some shared helper methods and member fields to subclasses.
 * <p>
 * An operations is a {@link Runnable} instance that is put on the {@link Agenda} during
 * the execution of a {@link com.je.bpm.engine.impl.interceptor.Command}.
 */
public abstract class AbstractOperation implements Runnable {

    protected CommandContext commandContext;
    protected Agenda agenda;
    protected ExecutionEntity execution;

    public AbstractOperation() {

    }

    public AbstractOperation(CommandContext commandContext, ExecutionEntity execution) {
        this.commandContext = commandContext;
        this.execution = execution;
        this.agenda = commandContext.getAgenda();
    }

    /**
     * Helper method to match the activityId of an execution with a FlowElement of the process definition referenced by the execution.
     */
    protected FlowElement getCurrentFlowElement(final ExecutionEntity execution) {
        if (execution.getCurrentFlowElement() != null) {
            return execution.getCurrentFlowElement();
        } else if (execution.getCurrentActivityId() != null) {
            String processDefinitionId = execution.getProcessDefinitionId();
            Process process = ProcessDefinitionUtil.getProcess(processDefinitionId);
            String activityId = execution.getCurrentActivityId();
            FlowElement currentFlowElement = process.getFlowElement(activityId, true);
            return currentFlowElement;
        }
        return null;
    }

    /**
     * Executes the execution listeners defined on the given element, with the given event type.
     * Uses the {@link #execution} of this operation instance as argument for the execution listener.
     */
    protected void executeExecutionListeners(HasExecutionListeners elementWithExecutionListeners, String eventType) {
        executeExecutionListeners(elementWithExecutionListeners, execution, eventType);
    }

    /**
     * Executes the execution listeners defined on the given element, with the given event type,
     * and passing the provided execution to the {@link com.je.bpm.engine.delegate.ExecutionListener} instances.
     */
    protected void executeExecutionListeners(HasExecutionListeners elementWithExecutionListeners, ExecutionEntity executionEntity, String eventType) {
        commandContext.getProcessEngineConfiguration().getListenerNotificationHelper().executeExecutionListeners(elementWithExecutionListeners, executionEntity, eventType);
    }

    /**
     * Returns the first parent execution of the provided execution that is a scope.
     */
    protected ExecutionEntity findFirstParentScopeExecution(ExecutionEntity executionEntity) {
        ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
        ExecutionEntity parentScopeExecution = null;
        ExecutionEntity currentlyExaminedExecution = executionEntityManager.findById(executionEntity.getParentId());
        while (currentlyExaminedExecution != null && parentScopeExecution == null) {
            if (currentlyExaminedExecution.isScope()) {
                parentScopeExecution = currentlyExaminedExecution;
            } else {
                currentlyExaminedExecution = executionEntityManager.findById(currentlyExaminedExecution.getParentId());
            }
        }
        return parentScopeExecution;
    }

    public CommandContext getCommandContext() {
        return commandContext;
    }

    public void setCommandContext(CommandContext commandContext) {
        this.commandContext = commandContext;
    }

    public Agenda getAgenda() {
        return agenda;
    }

    public void setAgenda(DefaultActivitiEngineAgenda agenda) {
        this.agenda = agenda;
    }

    public ExecutionEntity getExecution() {
        return execution;
    }

    public void setExecution(ExecutionEntity execution) {
        this.execution = execution;
    }

}
